//
//  MNDOpenDepositoryViewController.m
//  minidai
//
//  Created by 容贤郁 on 2018/3/14.
//  Copyright © 2018年 迷你金服. All rights reserved.
//

#import "MNDOpenDepositoryViewController.h"
#import <TTTAttributedLabel.h>
#import "MNDWebViewController.h"
#import "MNDDepositWebViewController.h"
#import "UIImage+JKColor.h"

@interface MNDOpenDepositoryViewController () <TTTAttributedLabelDelegate>

@property (weak, nonatomic) IBOutlet UITextField *realNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *idCardTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;

@property (weak, nonatomic) IBOutlet TTTAttributedLabel *authProtocolLabel;

@property (weak, nonatomic) IBOutlet TTTAttributedLabel *noticeLabel;

@end

@implementation MNDOpenDepositoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    __block UITextField *idTextField = self.idCardTextField;
    //现在18位身份证号码
    [self.idCardTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 18) {
            idTextField.text = [x substringToIndex:18];
        }
    }];
    
    __block UITextField *phoneTextField = self.phoneTextField;
    //限制11位手机号
    [self.phoneTextField.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        if (x.length > 11) {
            phoneTextField.text = [x substringToIndex:11];
        }
    }];
    
    [self addAgreementLabelAttribute];
    
    [self initialBackButton];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    UIImage *image = [UIImage jk_imageWithColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:0.3]];
    [self.navigationController.navigationBar setShadowImage:image];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)submitAction:(UIButton *)sender {
    if (self.realNameTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入真实姓名"];
        return;
    }
    
    if (self.idCardTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入身份证号码"];
        return;
    }
    
    if (self.phoneTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入银行预留手机号"];
        return;
    }
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    NSDictionary *param = [MNDSign signedParamWithDict:@{@"user_realname": self.realNameTextField.text, @"user_idcard": self.idCardTextField.text, @"user_mobile": self.phoneTextField.text, @"channel": @"app"}];
    [APIManager sendRequestWithPath:API_DEPOSIT_OPEN parameters:param method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"开通江西银行存管";
            webVC.fromNaviIndex = weakself.fromNaviIndex;
            
            [weakself.navigationController pushViewController:webVC animated:YES];
            
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)addAgreementLabelAttribute {
    
    //设置高亮颜色
    self.authProtocolLabel.highlightedTextColor = kColorOrange;
    //检测类型
    self.authProtocolLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    //代理
    self.authProtocolLabel.delegate = self;
    //不显示下划线
    self.authProtocolLabel.linkAttributes = @{(NSString *)kCTUnderlineStyleAttributeName: [NSNumber numberWithBool:NO]};
    
    NSString *text1 = @"点击提交表明您已阅读并同意《用户授权协议》《江西银行网络交易资金账户服务三方协议》";
    [self.authProtocolLabel setText:text1 afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        NSRange linkRange1 = [[mutableAttributedString string] rangeOfString:@"《用户授权协议》" options:NSCaseInsensitiveSearch];
        NSRange linkRange2 = [[mutableAttributedString string] rangeOfString:@"《江西银行网络交易资金账户服务三方协议》" options:NSCaseInsensitiveSearch];
        
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorOrange} range:linkRange1];
        [mutableAttributedString addAttributes:@{(NSString *)kCTForegroundColorAttributeName: kColorOrange} range:linkRange2];
        
        return mutableAttributedString;
    }];
    
    NSRange linkRange1 = [text1 rangeOfString:@"《用户授权协议》" options:NSCaseInsensitiveSearch];
    NSURL *url1 = [NSURL URLWithString:kUser_Grant_Protocol];
    NSRange linkRange2 = [text1 rangeOfString:@"《江西银行网络交易资金账户服务三方协议》" options:NSCaseInsensitiveSearch];
    NSURL *url2 = [NSURL URLWithString:kBank_Service_Protocol];
    [self.authProtocolLabel addLinkToURL:url1 withRange:linkRange1];
    [self.authProtocolLabel addLinkToURL:url2 withRange:linkRange2];
}

- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
    webVC.webViewUrl = url.absoluteString;
    webVC.loadType = LoadTypeLink;
    webVC.naviBarHidden = NO;
    if ([url.absoluteString isEqualToString: kUser_Grant_Protocol]) {
        webVC.title = @"用户授权协议";
    } else {
        webVC.title = @"江西银行网络交易资金账户服务三方协议";
    }
    
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:webVC];
    
    [self presentViewController:navVC animated:YES completion:^{
        
    }];
}

- (void)initialBackButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)backAction:(id)sender {
    UIViewController *viewController = self.navigationController.viewControllers[self.fromNaviIndex];
    [self.navigationController popToViewController:viewController animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
